<?php

namespace app\models;

use yii\db\ActiveRecord;

class Comments extends ActiveRecord
{

    /**
     * 写表
     * @param $content
     * @param $createTime
     * @return array
     */
    public static function add($content, $createTime)
    {
        $data = array(
            'content' => mb_substr($content, 0, 30),
            'create_time' => $createTime
        );

        self::getDb()
            ->createCommand()
            ->insert(self::tableName(), $data)
            ->execute();

        $data['id'] = self::getDb()->getLastInsertID();

        return $data;
    }

    /**
     * 分页搜索
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function search($page, $pageSize)
    {
        $query = self::find();

        $queryTotal = clone $query;

        $offset = ($page - 1) * $pageSize;
        $query->orderBy('id desc')
            ->offset($offset)
            ->limit($pageSize);

        $total = $queryTotal->count('id');
        $rows = $query->asArray()
            ->all();

        return [$rows, $total];
    }

}